//
//  ViewController.m
//  仿淘宝商品详情
//
//  Created by bxkj on 2017/11/27.
//  Copyright © 2017年 devil. All rights reserved.
//

#import "ViewController.h"
#import "LZBInifiteScrollView.h"
#import "Masonry.h"
#import "SDAutoLayout.h"
#import "UIButton+HQCustomIcon.h"
static NSString * const cellID = @"cellID";

@interface ViewController ()<LZBInifiteScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) LZBInifiteScrollView *carousel;
@property (nonatomic, assign) CGFloat detailOffsetY;
@property (nonatomic, strong)UIView * customView;
@property(nonatomic, strong) UITableView * tableView;

// 导航栏以及标题
@property (nonatomic, strong) UIView * backView;
@property (nonatomic, strong) UIButton  *backsButton;
@property (nonatomic, strong)  UIView * sharesView;
@property (nonatomic, strong)  UIButton  *sharesButton;
@property (nonatomic, strong) UIView * threeView;
@property (nonatomic, strong) UIButton *goodsButton;
@property (nonatomic, strong) UIButton *detailButton;
@property (nonatomic, strong) UIButton *pingjiaButton;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 初始化列表
    [self setTableView];
    // 导航栏
    [self setHeadNavigationView];
    // 底部视图
    [self setBottomView];
    // 让tableview加载完直接滚到最顶部
    [self.tableView  scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
}

#pragma mark--- 头部导航
- (void)setHeadNavigationView
{
    self.customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 103)];
    _customView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_customView];
    //左上角返回按钮
    self.backView = [[UIImageView alloc] init];
    _backView.userInteractionEnabled = YES;
    //    _backView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
    _backView.backgroundColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:0.7];
    _backView.layer.cornerRadius = 35/2;
    _backView.clipsToBounds = YES;
    [self.customView addSubview:_backView];
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(13);
        if (iPhoneX) {
            make.top.mas_equalTo(53);
        }else{
            make.top.mas_equalTo(29);
        }
        make.width.height.offset(35);
    }];
    self.backsButton = [[UIButton alloc] init];
    //    [_backsButton setTintColor:[UIColor grayColor]];
    [_backsButton setTintColor:[UIColor colorWithWhite:1 alpha:0.7]];
    UIImage *reftImage = [[UIImage imageNamed:@"circlesmore2_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_backsButton setImage:reftImage forState:UIControlStateNormal];
    [_backsButton setImage:reftImage forState:UIControlStateHighlighted];
    [_backsButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:_backsButton];
    [_backsButton mas_makeConstraints:^(MASConstraintMaker *make) {
        //        [make edges];
        make.left.top.offset(5);
        make.right.bottom.offset(-5);
    }];
    // 右上角分享
    self.sharesView = [[UIImageView alloc] init];
    _sharesView.userInteractionEnabled = YES;
    //    _sharesView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
    _sharesView.backgroundColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:0.7];
    _sharesView.layer.cornerRadius = 35/2;
    _sharesView.clipsToBounds = YES;
    [self.customView addSubview:_sharesView];
    [_sharesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-14);
        if (iPhoneX) {
            make.top.mas_equalTo(53);
        }else{
            make.top.mas_equalTo(29);
        }
        make.width.height.offset(35);
    }];
    self.sharesButton = [[UIButton alloc] init];
    //    [_sharesButton setTintColor:[UIColor grayColor]];
    [_sharesButton setTintColor:[UIColor colorWithWhite:1 alpha:0.7]];
    UIImage *rightImage = [[UIImage imageNamed:@"收藏白@2x"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [_sharesButton setImage:rightImage forState:UIControlStateNormal];
    [_sharesButton setImage:rightImage forState:UIControlStateHighlighted];
    [_sharesButton addTarget:self action:@selector(shareButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_sharesView addSubview:_sharesButton];
    [_sharesButton mas_makeConstraints:^(MASConstraintMaker *make) {
        //        [make edges];
        make.left.top.offset(6);
        make.right.bottom.offset(-6);
    }];
    //
    self.threeView = [[UIView alloc] init];
    _threeView.backgroundColor = [UIColor whiteColor];
    [self.customView addSubview:_threeView];
    [_threeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    [self setButtonsWithIndex:0 title:@"宝贝" superView:_threeView];
    [self setButtonsWithIndex:1 title:@"评价" superView:_threeView];
    [self setButtonsWithIndex:2 title:@"详情" superView:_threeView];
}
#pragma mark ---- 宝贝、详情、评价按钮
- (void)setButtonsWithIndex:(NSInteger)index title:(NSString *)title superView:(UIView *)superView{
    UIButton *btn = [[UIButton alloc]init];
    //默认样式
    NSMutableAttributedString *normalAttr = [[NSMutableAttributedString alloc] initWithString:title];
    NSDictionary *normalAttrDict = @{
                                     NSFontAttributeName:[UIFont systemFontOfSize:14.0f],
                                     NSForegroundColorAttributeName :[UIColor grayColor]
                                     };
    [normalAttr addAttributes:normalAttrDict range:NSMakeRange(0, title.length)];
    [btn setAttributedTitle:normalAttr forState:UIControlStateNormal];
    
    //选中样式
    NSMutableAttributedString *selectAttr = [[NSMutableAttributedString alloc] initWithString:title];
    NSDictionary *selectAttrDict = @{
                                     NSFontAttributeName:[UIFont systemFontOfSize:16.0f],
                                     NSForegroundColorAttributeName:[UIColor orangeColor]
                                     };
    [selectAttr addAttributes:selectAttrDict range:NSMakeRange(0, title.length)];
    [btn setAttributedTitle:selectAttr forState:UIControlStateSelected];
    
    btn.tag = index;
    
    [btn addTarget:self action:@selector(clickTitle:) forControlEvents:UIControlEventTouchUpInside];
    
    [superView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(superView).offset(index * (kScreenWidth / 3.0));
        make.top.bottom.equalTo(superView);
        make.width.mas_equalTo(@(kScreenWidth / 3.0));
    }];
    if (btn.tag == 0) {
        // 宝贝、详情、评价的按钮点击事件
        [self clickTitle:btn];
    }
    switch (btn.tag) {
        case 0:
            _goodsButton = btn;
            break;
        case 1:
            _pingjiaButton = btn;
            break;
        case 2:
            _detailButton = btn;
            break;
        default:
            break;
    }
}
// 宝贝、评价、详情点击事件
- (void)clickTitle:(UIButton *)sender{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:sender.tag] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark --- 返回上一页
- (void)backButtonClick:(UIButton *)button
{
    NSLog(@"返回上一页");
}
#pragma mark --- 分享内容
- (void)shareButtonClick:(UIButton *)button
{
    NSLog(@"分享本页内容");
}

#pragma mark ----- 创建头部轮播图以及实现代理方法
- (void)setHeadImage{
    self.tableView.tableHeaderView = self.carousel;
    self.carousel.placeholder = [UIImage imageNamed:@"LZBInifiteScrollView.bundle/placeHoder"];
    //设置滚动的图片数组，支持(里面可以存放UIImage对象、NSString对象【本地图片名】、NSURL对象【远程图片的URL】)
    self.carousel.images = @[[UIImage imageNamed:@"LZBInifiteScrollView.bundle/1"],@"LZBInifiteScrollView.bundle/2",@"LZBInifiteScrollView.bundle/3",[NSURL URLWithString:@"https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1916500820,874871263&fm=116&gp=0.jpg"]];
    self.carousel.foucsDelegate = self;
}
- (LZBInifiteScrollView *)carousel
{
    if(_carousel == nil)
    {
        _carousel = [[LZBInifiteScrollView alloc]init];
        _carousel.frame = CGRectMake(0, 0, 0, headViewHeight);
    }
    return _carousel;
}
#pragma mark --- 轮播图代理方法
- (void)lzbInifiteScrollView:(LZBInifiteScrollView *)foucsScrollView didSelectScrollViewIndex:(NSInteger)index
{
    NSLog(@"----%@,点击了第几张图片%ld",foucsScrollView,index);
}
#pragma mark --- 创建底部视图
- (void)setBottomView{
    UIView *bottomView = [[UIView alloc]init];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(@(kBottomHeight));
    }];
    
    
    // 创建自定义按钮
    UIButton *btn_click = [UIButton buttonWithType:UIButtonTypeCustom];
    //创建普通状态按钮图片
    [btn_click setImage:[UIImage imageNamed:@"customBack"]forState:UIControlStateNormal];
    //创建高亮或选中状态按钮图片
    [btn_click setImage:[UIImage imageNamed:@"home-selected"]forState:UIControlStateHighlighted];
    //设置按钮普通状态标题
    [btn_click setTitle:@"店铺"forState:UIControlStateNormal];
    // 设置按钮字体
    btn_click.titleLabel.font = [UIFont systemFontOfSize:14];
    //设置按钮普通状态标题颜色
    [btn_click setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    //设置按钮高亮或选中状态标题颜色
    [btn_click setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
    // 设置按钮背颜色
    [btn_click setBackgroundColor:[UIColor grayColor]];
    //按钮按下后的模糊状态
    [btn_click setAdjustsImageWhenHighlighted:NO];
    // 按钮坐标和尺寸
    
    btn_click.frame =CGRectMake(0,0, 50,49);
    
    [btn_click setIconInTop];
    [btn_click setIconInTopWithSpacing:3];
    // 加载按钮到视图
    [bottomView addSubview:btn_click];
    
    /*
    //按钮图片和标题总高度
    CGFloat totalHeight = (btn_click.imageView.frame.size.height + btn_click.titleLabel.frame.size.height);
    // 图片和标题相差距离
    CGFloat spaceHeight = 3;
    //设置按钮图片偏移
    [btn_click setImageEdgeInsets:UIEdgeInsetsMake(-(totalHeight - btn_click.imageView.frame.size.height),0.0, 0.0, -btn_click.titleLabel.frame.size.width)];
    //设置按钮标题偏移
    [btn_click setTitleEdgeInsets:UIEdgeInsetsMake(spaceHeight, -btn_click.imageView.frame.size.width, -(totalHeight - btn_click.titleLabel.frame.size.height),0.0)];
     // 加载按钮到视图
     [bottomView addSubview:btn_click];
     */
    
    
//    [self setBottomLeftButtonWithIndex:0 title:@"店铺" imageName:[UIImage imageNamed:@"icon"] superView:bottomView];
//    [self setBottomLeftButtonWithIndex:1 title:@"客服" imageName:[UIImage imageNamed:@"ic_consulting"] superView:bottomView];
    
    [self setBottomRightButtonWithIndex:0 title:@"加入购物车" color:[UIColor colorWithRed:253/255.0 green:179/255.0 blue:43/255.0 alpha:1.0] superView:bottomView];
    [self setBottomRightButtonWithIndex:1 title:@"立即购买" color:[UIColor colorWithRed:252/255.0 green:96/255.0 blue:32/255.0 alpha:1.0] superView:bottomView];
}
#pragma mark --- 店铺、客服以及加入购物车、立即购买
- (void)setBottomLeftButtonWithIndex:(NSInteger)index title:(NSString *)title imageName:(UIImage *)imageName superView:(UIView *)superView
{
    UIButton * button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.backgroundColor = [UIColor blueColor];
    [button2 setImage:imageName forState:UIControlStateNormal];
    [button2 setTitle:title forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1] forState:UIControlStateNormal];
    //    button2.titleLabel.font = [PFR13Font];
    button2.titleLabel.font = [UIFont systemFontOfSize:13];
    button2.tag = index;
    [superView addSubview:button2];
    [button2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(superView);
        make.left.equalTo(superView).offset(index * ((kScreenWidth/2.0-60) / 2.0));
        make.width.mas_equalTo((kScreenWidth/2.0 - 60) / 2.0);
        make.height.mas_equalTo((kScreenWidth/2.0 - 60) / 2.0);
    }];
   
    [button2 setIconInTopWithSpacing:5];
}
- (void)setBottomRightButtonWithIndex:(NSInteger)index title:(NSString *)title color:(UIColor *)color superView:(UIView *)superView{
    UIButton *btn = [[UIButton alloc]init];
    [btn setBackgroundColor:color];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    btn.tag = index;
    [superView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(superView).offset((kScreenWidth / 2.0) + (index * (kScreenWidth / 2.0 + 60) / 2.0) - 60);
        make.bottom.top.equalTo(superView);
        make.width.mas_equalTo(@((kScreenWidth / 2.0 + 60) / 2.0));
    }];
}
#pragma mark ---- 初始化列表视图
- (void)setTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kBottomHeight) style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.showsVerticalScrollIndicator = NO;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.estimatedRowHeight = 44;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    // 头部轮播图
    [self setHeadImage];
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

#pragma mark --- UITableViewDelegate，UITableViewDataSource
// 区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        return 40;
    }
}
// 区尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
// 分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
// 每个分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 20;
}
// 设置区头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]init];
    if (section == 0) {
        headerView.backgroundColor = [UIColor clearColor];
    }else{
        headerView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
        UILabel *label = [[UILabel alloc]init];
        NSDictionary *attrDict = @{
                                   NSFontAttributeName:[UIFont systemFontOfSize:12.0f],
                                   NSForegroundColorAttributeName:[UIColor blackColor]
                                   };
        NSMutableAttributedString *attr1 = [[NSMutableAttributedString alloc]initWithString:@"------宝贝------" attributes:attrDict];
        NSMutableAttributedString *attr2 = [[NSMutableAttributedString alloc]initWithString:@"------评价------" attributes:attrDict];
        NSMutableAttributedString *attr3 = [[NSMutableAttributedString alloc]initWithString:@"------详情------" attributes:attrDict];
        switch (section) {
            case 0:
                label.attributedText = attr1;
                break;
            case 1:
                label.attributedText = attr2;
                break;
            case 2:
                label.attributedText = attr3;
                break;
            default:
                break;
        }
        [headerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headerView);
            make.centerX.equalTo(headerView);
        }];
    }
    return headerView;
}
// 设置cell上显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"商品%zd",indexPath.row];
    return cell;
}

#pragma mark NavigationBar
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([object isEqual:self.tableView] && [keyPath isEqualToString:@"contentOffset"]) {
        [self refreshNavigationBar];
    }
}
- (void)refreshNavigationBar {
    CGPoint offset = self.tableView.contentOffset;
    NSLog(@"%@",NSStringFromCGPoint(offset));
    CGFloat offsetY = offset.y;
    if (offset.y < 0) {
        
    } else if (offset.y == 0) {
        [self xialaChangeNavi:offsetY];
        // 导航栏左右按钮变换颜色
        self.backView.backgroundColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:0.7];
        [self.backsButton setTintColor:[UIColor colorWithWhite:1 alpha:0.7]];
        self.sharesView.backgroundColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:0.7];
        [self.sharesButton setTintColor:[UIColor colorWithWhite:1 alpha:0.7]];
    } else {
        [self xialaChangeNavi:offsetY];
        // 导航栏左右按钮变换颜色
        self.backView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
        [self.backsButton setTintColor:[UIColor darkGrayColor]];
        self.sharesView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
        [self.sharesButton setTintColor:[UIColor darkGrayColor]];
    }
}
- (void)xialaChangeNavi:(CGFloat)offY
{
    //通过offset.y与 图片高度 减去自定义头部高度再减去图片下标的偏移量 比例来决定透明度
    CGFloat alpha = MIN(1, fabs(offY/(AlphaOffSet - offY)));
    self.customView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:alpha];
    self.threeView.alpha = alpha;
    NSIndexPath *indexPath = [self.tableView indexPathsForVisibleRows][0];
    switch (indexPath.section) {
        case 0:
            _goodsButton.selected = YES;
            _detailButton.selected = NO;
            _pingjiaButton.selected = NO;
            break;
        case 1:
            _goodsButton.selected = NO;
            _pingjiaButton.selected = YES;
            _detailButton.selected = NO;
            break;
        case 2:
            _goodsButton.selected = NO;
            _pingjiaButton.selected = NO;
            _detailButton.selected = YES;
            break;
        default:
            break;
    }
}
// 试图将要出现的时候刷新导航内容
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshNavigationBar]; // 刷新高度以判断导航是透明还是不透明的
    [self.tableView addObserver:self forKeyPath:@"contentOffset"
                        options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
                        context:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.tableView removeObserver:self
                        forKeyPath:@"contentOffset"];
}

- (CGFloat)detailOffsetY {
    //这个应该是可以计算出来的 ，还没想出来
    if (UI_IS_IPHONE4 || UI_IS_IPHONE5) {
        _detailOffsetY = 210;
    } else if (UI_IS_IPHONE6_OR_7) {
        _detailOffsetY = 236;
    } else if (UI_IS_IPHONE6PLUS_OR_7PLUS){
        _detailOffsetY = 260;
    } else {
        _detailOffsetY = 236;
    }
    return _detailOffsetY;
}



@end
